<template>
  <div class="map-container" style="margin-top: 0;">
    <iframe v-if="gisUrl" id="iframeContainer" :src="gisUrl" frameborder="0" scrolling="no" height="100%" width="100%" />
  </div>
</template>
<script setup>
import { ref, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { useUserStore } from '@/pinia/modules/user'
const props = defineProps({
  options: {
    type: Object,
    default: { stagesItem: '', lineListItem: '' }
  },
  selectLandsId: {
    type: Array,
    default: []
  },
  selectLandArrayList: {
    type: Array,
    default: []
  }
})

const userStore = useUserStore()
const emit = defineEmits(['close'])

onMounted(async () => {
  initMap()
})

// #region 地图相关
const gisUrl = ref('')
let iframeDom
const initMap = () => {
  const baseUrl = import.meta.env.VITE_GIS_PAGE
  const userId = userStore.userInfo.userId
  const companyId = userStore.userInfo.companyId
  const farmId = userStore.userInfo.farmId
  const planId = props.options.lineListItem && props.options.lineListItem.plantingPlanId ? props.options.lineListItem.plantingPlanId : ''
  const selectedLand = props.options.lineListItem && props.options.lineListItem.selectLands ? props.options.lineListItem.selectLands.map(item => item.farmLandNo).join(',') : ''
  gisUrl.value = `${baseUrl}/land/project?userId=${userId}&companyId=${companyId}&farmId=${farmId}&selectedLand=${selectedLand}&planId=${planId}&toolPanelVisible=0`
  nextTick(() => {
    iframeDom = document.querySelector('#iframeContainer')
    window.addEventListener('message', getMes)
  })
}

const getMes = (event) => {
  const { data: { type, params } } = event
  if (type == 'selectedLand') {
    const list = JSON.parse(params)
    if (list.length < 1) {
      return message('请添加地块', 3)
    }
    props.options.lineListItem.selectLands = []
    const landNames = []
    let totalArea = 0
    list.forEach(item => {
      props.options.lineListItem.selectLands.push(item)
      totalArea += item.mapAreaSize
    })
    const total = list.length
    const str = `${total}块地，${totalArea.toFixed(1)}亩`
    props.options.lineListItem.farmLandName = str
    emit('close')
  } else if (type == 'close') {
    emit('close')
  }
}
onBeforeUnmount(() => {
  destory()
})
const destory = () => {
  window.removeEventListener('message', getMes)
}
// #endregion
</script>
<style lang="scss" scoped>
.map-container {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 999;
}
</style>
